package cn.itcast.music.helper;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.itcast.music.entity.Music;

@SuppressLint("Range")
public class MusicHelper extends BaseHelper {

    public MusicHelper(Context context) {
        super(context);
    }

    public Music insert(Music music) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", music.getTitle());
        values.put("artist", music.getArtist());
        values.put("album", music.getAlbum());
        values.put("path", music.getPath());
        values.put("duration", music.getDuration());
        values.put("size", music.getSize());
        int id = (int) db.insert("music", null, values);
        db.close();
        return new Music(id, music.getTitle(), music.getArtist(),
                music.getAlbum(), music.getPath(), music.getDuration(),
                music.getSize());
    }

    public void deleteAll() {
        SQLiteDatabase db = getWritableDatabase();
        db.delete("music", null, null);
        db.close();
    }

    public Music selectById(int id) {
        SQLiteDatabase db = getReadableDatabase();
        Music music = null;
        try (Cursor cursor = db.rawQuery("SELECT * FROM music WHERE id = ?",
                new String[]{String.valueOf(id)})) {
            if (cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndex("title"));
                String artist = cursor.getString(
                        cursor.getColumnIndex("artist"));
                String album = cursor.getString(cursor.getColumnIndex("album"));
                String path = cursor.getString(cursor.getColumnIndex("path"));
                long duration = cursor.getLong(
                        cursor.getColumnIndex("duration"));
                long size = cursor.getLong(cursor.getColumnIndex("size"));
                music = new Music(title, artist, album, path, duration, size);
            }
        }
        return music;
    }

}
